package com.leyou.user.interceptors;

import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
public class TokenCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties props;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1,获取到请求头中的token

        String token = request.getHeader("heima95");

        //2,解析比对token

        Payload<AppInfo> infoFromToken = null;
        AppInfo info = null;
        try {
            infoFromToken = JwtUtils.getInfoFromToken(token, props.getPublicKey(), AppInfo.class);
            info = infoFromToken.getInfo();
            log.info("【用户服务】成功解析到{}的请求",info.getServiceName());
        } catch (Exception e) {
            log.error("【用户服务】正遭受非法请求");
            return false;
        }

        //token可以解析，但是请求的目标服务id不包含当前服务id，则也要拒绝
        if (!info.getTargetList().contains(1L)){
            log.error("【用户服务】正遭受非法请求");
            return false;
        }

        return true;
    }
}
